//
//  AppDelegate.m
//  linkingGame
//
//  Created by zw wu on 15/4/4.
//  Copyright (c) 2015年 com.jinWu. All rights reserved.
//

#import "AppDelegate.h"
#import "RootViewController.h"
#import "MobClick.h"

#define kUMAnalyticsAppkey @"551f954afd98c514af000132"
#define kUMAnalyticsChannelId @"App Store"
#define kDispIconUpdateWarn @"kDispIconUpdateWarn"

//定义更新链接保存在本地的字段
#define kUpdateLinkForPlistKey @"kUpdateLinkForPlistKey"

//定义上次更新时间保存在本地的字段
#define kLastUptateTimeForPlistKey     @"kLastUptateTimeForPlistKey"

//定义1天的时间的秒数
#define kOneDayTime 86400

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    self.window.backgroundColor = [UIColor whiteColor];
    
    RootViewController *rootVC = [[RootViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:rootVC];
    rootVC.navigationController.navigationBarHidden = YES;
    self.window.rootViewController = nav;
    [nav release];
    [rootVC release];
    
    [self.window makeKeyAndVisible];
    
    //添加数据统计的功能
    [MobClick startWithAppkey:kUMAnalyticsAppkey
                 reportPolicy:(ReportPolicy)SEND_ON_EXIT
                    channelId:kUMAnalyticsChannelId];
    
    [MobClick checkUpdateWithDelegate:self selector:@selector(autoMobClickCallBack:)];
    
    //设置是否打印收集的数据
    [MobClick setLogEnabled:YES];
    
    return YES;
}

- (void)autoMobClickCallBack:(id)sender
{
    BOOL isUpdate = [[sender objectForKey:@"update"] boolValue];
    if (isUpdate)
    {
        BOOL isUpdate = [[sender objectForKey:@"update"] boolValue];
        if (isUpdate)
        {
            // 图标升级提醒，有升级提醒时图标显示1，打开程序后不管是否升级，图标数字均取消
            BOOL bDispIconWarn = false;
            bDispIconWarn = [[NSUserDefaults standardUserDefaults] boolForKey:kDispIconUpdateWarn];
            if (bDispIconWarn)
            {
                [UIApplication sharedApplication].applicationIconBadgeNumber = 1;
            }
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kDispIconUpdateWarn];
            
            //判断是否与上次弹窗的时间间隔了1天，注意都是按照美国时间比较的
            double lastUpdateTime = [[NSUserDefaults standardUserDefaults] doubleForKey:kLastUptateTimeForPlistKey];
            double nowTime = [[NSDate date] timeIntervalSince1970];
            if ((lastUpdateTime >0) && (nowTime - lastUpdateTime < kOneDayTime))
            {
                return;
            }
            
            [[NSUserDefaults standardUserDefaults] setDouble:nowTime forKey:kLastUptateTimeForPlistKey];
            
            //提取服务器返回的信息，弹出提示框
            NSString *path = [sender objectForKey:@"path"];
            [[NSUserDefaults standardUserDefaults] setObject:path forKey:kUpdateLinkForPlistKey];
            NSString *version = [sender objectForKey:@"version"];
            
            NSString *tipTitle = NSLocalizedString(@"VERSION_UPDATE_TIP_TITLE",@"");
            NSString *tipMsg = NSLocalizedString(@"VERSION_UPDATE_TIP_MSG",@"");
            NSString *tipCancelBtnTitle = NSLocalizedString(@"VERSION_UPDATE_TIP_CANCELBTN",@"");
            NSString *tipOtherBtnTitle = NSLocalizedString(@"VERSION_UPDATE_TIP_OTHERBTN",@"");
            
            if (IOS_VERSION_8_OR_ABOVE)
            {
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:tipCancelBtnTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                }];
                
                UIAlertAction *updateAction = [UIAlertAction actionWithTitle:tipOtherBtnTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    NSString *path = [[NSUserDefaults standardUserDefaults] objectForKey:kUpdateLinkForPlistKey];
                    if (path.length > 0)
                    {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:path]];
                    }
                }];
                
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:tipTitle
                                                                                         message:[NSString stringWithFormat:tipMsg,version]
                                                                                  preferredStyle:UIAlertControllerStyleAlert];
                [alertController addAction:cancelAction];
                [alertController addAction:updateAction];
                [self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
            }
            else
            {
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:tipTitle
                                                                   message:[NSString stringWithFormat:tipMsg,version]
                                                                  delegate:self
                                                         cancelButtonTitle:tipCancelBtnTitle
                                                         otherButtonTitles:tipOtherBtnTitle, nil];
                [alertView show];
                [alertView release];
            }
        }
        else
        {
            [UIApplication sharedApplication].applicationIconBadgeNumber = 0;   // hide
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kDispIconUpdateWarn];
        }
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (1 == buttonIndex)
    {
        NSString *path = [[NSUserDefaults standardUserDefaults] objectForKey:kUpdateLinkForPlistKey];
        if (path.length > 0)
        {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:path]];
        }
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if (url != nil)
    {
        NSString *path = [url absoluteString];
        NSMutableString *string = [[NSMutableString alloc] initWithString:path];
        if ([path hasPrefix:@"file://"])
        {
            [string replaceOccurrencesOfString:@"file://" withString:@"" options:NSCaseInsensitiveSearch  range:NSMakeRange(0, path.length)];
        }
        NSString* fileName = [path lastPathComponent];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDir = [paths objectAtIndex:0];
        NSString *imageFilePath = [docDir stringByAppendingPathComponent:fileName];
        
        NSArray* imageDataArr = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        for(int i = 0; i < imageDataArr.count; ++i)
        {
            NSString* imagePath = [imageFilePath stringByAppendingString:[NSString stringWithFormat:@"%@_%d@2x.png", fileName, i + 1]];
            [fileManager createFileAtPath:imagePath contents:(NSData*)imageDataArr[i] attributes:nil];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:addGameImagesNotify object:nil userInfo:nil];
    }
    return YES;
}




@end
